//package cn.edu.zut.score.filter;
//
//import cn.edu.zut.score.core.cache.RedisCache;
//import cn.edu.zut.score.core.constant.RoleEnum;
//import cn.edu.zut.score.core.domain.RestResponse;
//import cn.edu.zut.score.core.entity.User;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import lombok.extern.slf4j.Slf4j;
//
//import javax.servlet.*;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.io.IOException;
//
///**
// * @author zby
// * @date 2021/08/10
// */
//@Slf4j
//public class ApiFilter implements Filter {
//
//    private final RedisCache redisCache;
//
//    public ApiFilter(RedisCache redisCache) {
//        this.redisCache = redisCache;
//    }
//
//    @Override
//    public void init(FilterConfig filterConfig) {
//        log.info("api过滤器已创建");
//    }
//
//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        String token = request.getHeader("Authorization");
//        String uri = request.getRequestURI();
//        if (token != null && !"/score/api/info".equals(uri) && !"/logout".equals(uri)) {
//            User currentUser = redisCache.getCurrentUser(token);
//            boolean flag = (uri.startsWith("/score/api/admin") && !currentUser.getRole().equals(RoleEnum.admin.getCode())) ||
//                    (uri.startsWith("/score/api/teacher") && !currentUser.getRole().equals(RoleEnum.teacher.getCode())) ||
//                    (uri.startsWith("/score/api/student") && !currentUser.getRole().equals(RoleEnum.student.getCode()));
//            if (flag) {
//                log.info("{}进行的操作{}无权限", currentUser.getId(), uri);
//                response.setHeader("Access-Control-Allow-Origin", "*");
//                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
//                response.setHeader("Access-Control-Max-Age", "3600");
//                response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
//                response.setContentType("application/json;charset=UTF-8");
//                ObjectMapper objectMapper = new ObjectMapper();
//                response.getWriter().write(objectMapper.writeValueAsString(RestResponse.fail("权限不足")));
//                return;
//            }
//        }
//        filterChain.doFilter(servletRequest, servletResponse);
//    }
//
//    @Override
//    public void destroy() {
//        log.info("api过滤器已销毁");
//    }
//}
